package _11_整理题目._6_模拟设计._竖式计算;

import org.junit.Test;
import util.ListNode;

import java.util.Stack;


/**
 * 先将 两个链表中的值 压栈
 * 
 * 然后逐个弹出，求和，模仿 _03_大数加法 过程
 * 
 */
public class _04_两个链表生成相加链表 {
    
    public ListNode addInList (ListNode head1, ListNode head2) {
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        while (head1!=null || head2!=null) {
            if (head1!=null) {
                stack1.push(head1.val);
                head1 = head1.next;
            }
            if (head2!=null) {
                stack2.push(head2.val);
                head2 = head2.next;
            }
        }
    
        ListNode finalNode = null;
        ListNode tail = finalNode;
        int x, y, carry=0;
        while (!stack1.isEmpty() || !stack2.isEmpty() || carry!=0) {
            
            if (stack1.isEmpty()) {
                x = 0;
            } else {
                x = stack1.pop();
            }
            if (stack2.isEmpty()) {
                y = 0;
            } else {
                y = stack2.pop();
            }
            
            int sum = x + y + carry;
            carry = sum / 10;
            ListNode node = new ListNode(sum % 10);
            node.next = tail;
            tail = node;
        }
        return tail;
    }
    
    @Test
    public void main() {
        Integer[] input1 = {9, 3, 7};
        Integer[] input2 = {6, 3};
        ListNode head1 = ListNode.getListFromArray(input1);
        ListNode head2 = ListNode.getListFromArray(input2);
        ListNode result = addInList(head1, head2);
        ListNode.printList(result);
    }
    
}
